#!/usr/bin/env python

#Author: Rafael Soares
#License: GNU GPL v3
#Oficial Source: http://code.google.com/p/youshell/
#Version: 1.3

import sys
import urllib2
from xml.dom import minidom
import os
import time
import urllib2
import subprocess
import signal

src_youtubedl = None

def signal_handler(signal, frame):
    globals()['src_youtubedl'].kill()
    sys.exit(0)

def exec_video(link, best_quality):
    args_youtubedl = [os.getcwd()+'/lib/youtube-dl','-o','/tmp/video','-q']
    if(best_quality == False):
        args_youtubedl.append('-f')
        args_youtubedl.append('18')

    args_youtubedl.append(str(link))

    subprocess.Popen(['rm','-f','/tmp/video.part'])
    #import pdb; pdb.set_trace()
    globals()['src_youtubedl'] = subprocess.Popen(args_youtubedl)

    print '\n======= Loading... '+link+' =======\n'
    
    while(os.path.exists('/tmp/video.part') == False):
        time.sleep(7)

    while(os.path.getsize('/tmp/video.part') < 1200000):
        time.sleep(5)

    subprocess.Popen('mplayer -really-quiet /tmp/video.part', shell=True)
    signal.signal(signal.SIGINT, signal_handler)
    signal.pause()

def get_xml_youtube(search_args):
    return minidom.parse(urllib2.urlopen("http://gdata.youtube.com/feeds/api/videos?vq="+search_args+"&racy=include&orderby=relevance" ))

def show_results_menu(search_args):
    xml = get_xml_youtube(search_args)
    iterator_xml_first = xml.firstChild.childNodes.__iter__()

    count = 1
    links = list()

    for row in iterator_xml_first:
        iterator_xml_second = row.childNodes.__iter__()

        iter_title = row.getElementsByTagName('title').__iter__()
        for title_row in iter_title:
            print str(count)+' - '+title_row.childNodes[0].toxml()
            count+=1
            
        iter_link = row.getElementsByTagName('link').__iter__()
        for link_row in iter_link:
            if(link_row.attributes["href"].value.find('http://www.youtube.com') == 0):
                links.append(link_row.attributes["href"].value)

    
    while True:
        num_link = raw_input('Type the number of result you wanna watch.(\'q\' to exit) > ');

        if(num_link == 'q') or (num_link == 'quit') or (num_link == 'exit'):
            sys.exit()
        elif(num_link.isdigit() == False) or (int(num_link) < 1) or (int(num_link) > count):
            print '\nInvalid number. Try Again.\n'
            continue
        else:
            break

    return links[int(num_link)-1]

def main():

    iterator_argv = sys.argv.__iter__()
    url = None
    best_quality = False

    for arg in iterator_argv: 
        if(arg == '-s'):
            search_args = iterator_argv.next().replace(' ','+')
            url = show_results_menu(search_args)

        if(arg == '-u'):
            url = iterator_argv.next()

        if(arg == '-b'):
            best_quality = True

    if (url == None):
        print '\nError: Try to type -s or -u argument\n'
        sys.exit()

    exec_video(url, best_quality)

main()





